<template>
  <div class="login">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "../../utils/request";
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(ref) {
      this.$refs[ref].validate(valid => {
        if (valid) {
          axios({
            url: "/api/login",
            method: "post",
            data: this.ruleForm
          }).then(res => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "success"
            });
            if (res.data.code !== 1) return;
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("username", res.data.data.username);
            localStorage.setItem("id", res.data.data.id);
            this.$router.push("/page");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(ref) {
      this.$refs[ref].validate(valid => {
        if (valid) {
          axios({
            url: "/api/resolve",
            method: "post",
            data: this.ruleForm
          }).then(res => {
            localStorage.setItem("token", res.data.token);
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "success"
            });
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style>
</style>